//! Test framework converted from C

use std::sync::atomic::{AtomicUsize, Ordering};
use std::alloc::{GlobalAlloc, Layout, System};

/// Tracks memory allocations for testing memory leaks
static ALLOCATED: AtomicUsize = AtomicUsize::new(0);
static ALLOC_LIMIT: AtomicUsize = AtomicUsize::new(usize::MAX);

#[global_allocator]
static ALLOCATOR: TestingAllocator = TestingAllocator;

/// Custom allocator that tracks allocations and can enforce limits
struct TestingAllocator;

unsafe impl GlobalAlloc for TestingAllocator {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        // Track allocation attempt
        let count = ALLOCATED.fetch_add(layout.size(), Ordering::SeqCst);
        let limit = ALLOC_LIMIT.load(Ordering::SeqCst);

        // Check if we've hit the allocation limit
        if count >= limit {
            ALLOCATED.fetch_sub(layout.size(), Ordering::SeqCst);
            return std::ptr::null_mut();
        }

        // Perform allocation and initialize with garbage pattern
        let ptr = System.alloc(layout);
        if !ptr.is_null() {
            std::ptr::write_bytes(ptr, 0xBA, layout.size());
        }
        ptr
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        // Write free pattern before deallocation
        std::ptr::write_bytes(ptr, 0xDE, layout.size());
        ALLOCATED.fetch_sub(layout.size(), Ordering::SeqCst);
        System.dealloc(ptr, layout);
    }
}

/// Functions for managing allocation testing
pub fn set_alloc_limit(limit: isize) {
    if limit < 0 {
        ALLOC_LIMIT.store(usize::MAX, Ordering::SeqCst);
    } else {
        ALLOC_LIMIT.store(limit as usize, Ordering::SeqCst);
    }
}

pub fn get_allocated() -> usize {
    ALLOCATED.load(Ordering::SeqCst)
}

/// Unit test wrapper
pub struct UnitTest(pub fn());

/// Run a list of unit tests
pub fn run_tests(tests: &[UnitTest]) {
    for test in tests {
        // Reset limits for each test
        set_alloc_limit(-1);
        
        // Run the test
        (test.0)();
        
        // Verify no memory leaks
        assert_eq!(get_allocated(), 0, "Memory leak detected");
    }
}

/// Macro for creating test lists
#[macro_export]
macro_rules! test_list {
    ($($test_fn:expr),* $(,)?) => {{
        &[$($crate::test_framework::UnitTest($test_fn)),*]
    }};
}

